package com.jerry.token.model;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Filename:    com.lngtop.vo.TokenModel
 * Description:
 * Copyright:   Copyright (c)2017
 * Company:     lngtop
 *
 * @author: 谢余锋
 * @version: 1.0
 * Create at:   2017/1/20 下午4:24
 * <p/>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2017/1/20      谢余锋        1.0        1.0 Version
 */
public class TokenModel implements Serializable {

    private String userId;

    private String userName;

    private String token;

    public TokenModel() {
    }

    public TokenModel(String userId, String userName, String token) {
        this.userId = userId;
        this.userName = userName;
        this.token = token;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }


    /* ==================== static ==================== */
    private static Pattern tokenPattern = Pattern.compile("([^=]*)=([^&]*)&?");

    public static TokenModel create() {
        return new TokenModel();
    }

    public static TokenModel parse(String tokenString) {
        if (tokenString == null) {
            return null;
        }
        TokenModel token = new TokenModel();
        Map<String, Object> map = new HashMap<String, Object>();
        for (Matcher m = tokenPattern.matcher(tokenString); m.find(); ) {
            String key = m.group(1);
            Object value = m.group(2);
            map.put(key, value);
        }
        token.setUserId(map.get("userId").toString());
        token.setUserName(map.get("userName").toString());
        token.setToken(map.get("token").toString());
        return token;
    }

    public static String format(TokenModel token) {
        if (token == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();

        sb.append("userId=").append(token.getUserId());
        sb.append("&userName=").append(token.getUserName());
        sb.append("&token=").append(token.getToken());
        return sb.toString();
    }
}
